package com.yiyi.credit.manage.sso.service.inner;

import com.yiyi.credit.manage.sso.cache.RedisManager;
import com.yiyi.credit.manage.sso.common.constants.RedisConstants;
import com.yiyi.credit.manage.sso.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;


@Service
public class TokenServiceImpl implements TokenService {

    //private static Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);

    @Autowired
    RedisManager redisManager;

    @Override
    public String generatorToken(Long userId, Long expire) {

        // 判断是否生成过token
        String tokenUid = getTokenUidKey(userId);
        String oldToken = redisManager.get(tokenUid);
        if (StringUtils.isNotBlank(oldToken)) {
            redisManager.delete(oldToken);
        }
        String token = getTokenKey();
        redisManager.set(token, String.valueOf(userId), expire);
        redisManager.set(tokenUid, token, expire);
        return token;
    }

    private static String generatorToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    @Override
    public void delToken(String token) throws ServiceException {
        String userId = redisManager.get(token);
        String tokenUid = getTokenUidKey(userId);
        redisManager.delete(token);
        redisManager.delete(tokenUid);
    }


    @Override
    public Long getUidByToken(String token) throws ServiceException {
        //String value = redisManager.get(RedisConstants.TOKEN + token);
        String value = redisManager.get(token);
        if (StringUtils.isNotBlank(value)) {
            return Long.valueOf(value);
        }
        return null;
    }


    @Override
    public Boolean verifyToken(String token) throws ServiceException {
        Long uid = getUidByToken(token);
        if (uid != null) {
            String tokenUidKey = getTokenUidKey(uid);
            String redisToken = redisManager.get(tokenUidKey);
            if (StringUtils.isNotBlank(redisToken) && token.equals(redisToken)) {
                return true;
            }
        }
        return false;
    }

    private String getTokenKey() {
        return RedisConstants.TOKEN + generatorToken();
    }

    private String getTokenUidKey(Object userId) {
        return RedisConstants.USER_ID + userId;
    }
}
